/**
 * [application common section] begin
 */
G_VARS = {};

function common_init() {
    dbg('dev');

    var gotopl = 963;
    var wrap = $(document.body).children('.dhWrap');
    if (wrap.length == 0) {
        wrap = $(document.body).children('#wrapper');
        gotopl = 913;
    }
    if (wrap.length == 0) return;
    var dom = $('#goTop').parent().parent();
    var domh = dom.height();
    var doc = document;

    function resetTop() {
        var l = wrap.offset().left + gotopl;
        var wnd = window;
        var doc = document;
        var vrh = Math.min(doc.body.scrollHeight, doc.documentElement.clientHeight || doc.body.clientHeight || wnd.innerHeight || doc.height || 0);
        dom.css('left', l);
        if ($.browser.msie && parseInt($.browser.version) < 7) {
            var t = $(doc).scrollTop() + vrh - domh - 21;
            dom.css('top', t);
        }
    }

    function domShow(e) {
        if ($(window).scrollTop()) dom.show();
        else
        dom.hide();
    }

    function resetAndShow(e) {
        resetTop();
        domShow();
        if (typeof(G_VARS.head_tip) != 'undefined') G_VARS.head_tip.adjust();
    }

    if ($.browser.msie) {
        if (parseInt($.browser.version) < 7) {
            dom.css('position', 'absolute');
            window.attachEvent('onscroll', resetAndShow);
            resetTop();
        } else {
            window.attachEvent('onscroll', resetAndShow);
        }
        domShow();
    } else {
        window.addEventListener("scroll", domShow, false);
        domShow();
    }
    $(window).bind('resize', resetAndShow);
    setInterval(resetAndShow, 6000);
    resetTop();
    domShow();
    setTimeout(function () {
        $(':button').hover(function () {
            if (this.className.indexOf('Gray') != -1) return;
            var mat = this.className.match(/^submit([a-zA-Z\d]+)/);
            if (mat) {
                $(this).addClass('submit' + mat[1] + 'C');
            }
        }, function () {
            var mat = this.className.match(/^submit([a-zA-Z\d]+)/);
            if (mat) {
                $(this).removeClass('submit' + mat[1] + 'C');
            }
        })
    }, 3000);
}

function twCheckLogon(show_dlg) {
    var lgon = 1;
    return lgon;
}

var is_dbg = -1;

function dbg(s) {
    if (-1 == is_dbg) is_dbg = $.cookie('develop') ? 1 : 0;
    if (is_dbg) {
        if ('undefined' == typeof(s)) s = 'undefined';
        if (null == s) s = 'null';
        if (!s.toString) s = 'object';
        $.dbgln(s);
    }
}

function dbg_exp(e) {
    if (-1 == is_dbg) is_dbg = $.cookie('develop') ? 1 : 0;
    if (is_dbg) {
        if ('undefined' == typeof(s)) s = 'undefined';
        if (null == s) s = 'null';
        if (!s.toString) s = 'object';
        $.dbgln(' ');
        $.dbgln('****exception begin****');
        $.dbgObj(e);
        $.dbgln('****exception end****');
        $.dbgln(' ');
    }
}

function getRandom() {
    return Math.random().toString().substr(2, 5);
}

G_ERROR = [{
    id: 0,
    msg: "正确。"
}, {
    id: 1,
    msg: "服务器出错，请稍后再试。"
}, {
    id: 2,
    msg: "填写内容错误。"
}, {
    id: 3,
    msg: "权限不足。"
}, {
    id: 0x110,
    msg: "此邮箱已被他人注册使用。"
}, {
    id: 0x111,
    msg: "邮箱或密码错误。"
}, {
    id: 0x112,
    msg: "您还没有登录。"
}, {
    id: 0x113,
    msg: "此邮箱未被注册使用。"
}, {
    id: 0x114,
    msg: "密码重置链接已过期。"
}, {
    id: 0x115,
    msg: "您的账户已被冻结。"
}, {
    id: 0x116,
    msg: "您的账户已被封停。"
}, {
    id: 0x120,
    msg: "此用户名已被他人注册使用。"
}, {
    id: 0x210,
    msg: "帖子不存在或已被删除。"
}, {
    id: 0x211,
    msg: "权限不足。"
}, {
    id: 0x310,
    msg: "你没有权限编辑此书籍。"
}, {
    id: 0x311,
    msg: "此书已经被富途网收录，无需上传。"
}, {
    id: 0x312,
    msg: "您的等级不满足下载此书的最低要求。"
}, {
    id: 0x313,
    msg: "您的积分不足。"
}, {
    id: 0x314,
    msg: "本书正在审核中。"
}, {
    id: 0x315,
    msg: "本书未通过审核。"
}, {
    id: 0x510,
    msg: "用户不存在"
}, {
    id: 0x511,
    msg: "您最多关注10个话题"
}, {
    id: 0x512,
    msg: "不能向未收听你的用户发送私信"
}, {
    id: 0x513,
    msg: "已达到可关注股票上限。"
}, {
    id: 0x514,
    msg: "已达到可关注上限，您最多可关注1000个人。"
}, {
    id: 0x610,
    msg: "你没有权限编辑此报告。"
}, {
    id: 0x611,
    msg: "此报告已经被富途网收录，无需上传。"
}, {
    id: 0x612,
    msg: "您的等级不满足下载此报告的最低要求。"
}, {
    id: 0x613,
    msg: "您的积分不足。"
}, {
    id: 0x614,
    msg: "本报告正在审核中。"
}, {
    id: 0x615,
    msg: "本报告未通过审核。"
}];

function errorInfo(id) {
    for (var idx in G_ERROR) {
        if (G_ERROR[idx].id == id) {
            return G_ERROR[idx];
        }
    }
    return {
        'id': id,
        msg: '未知错误'
    };
}

function showLogonDlg(opt) {}

function msgBanner(opt) {
    opt = $.extend({
        dom: null,
        method: 'after',
        msg: '提示',
        tm: 5000,
        style: 'Err'
    }, opt);
    if (null == opt.dom) return msgBox({
        title: '提示',
        msg: opt.msg,
        cancel_t: '',
        type: 'alert'
    });
    var dom = $('<div name="msg_banner" class="hide msgBox' + opt.style + '"></div>').html(opt.msg);
    switch (opt.method) {
    case 'prepend':
        opt.dom.children('[name=msg_banner]').remove();
        opt.dom.prepend(dom);
        break;
    case 'append':
        opt.dom.children('[name=msg_banner]').remove();
        opt.dom.append(dom);
        break;
    case 'before':
        opt.dom.prev('[name=msg_banner]').remove();
        opt.dom.before(dom);
        break;
    case 'after':
        opt.dom.next('[name=msg_banner]').remove();
        opt.dom.after(dom);
        break;
    default:
        return;
    }
    var tid = opt.dom.attr('timer');
    if (typeof(tid) != 'undefined') clearTimeout(tid);
    var need_top = opt.dom.offset().top;
    var cur_top = $(window).scrollTop();
    if (cur_top > need_top) $(window).scrollTop(need_top);
    dom.slideDown();
    var tid = setTimeout(function () {
        dom.slideUp();
    }, opt.tm);
    opt.dom.attr('timer', tid);
}

function msgBox(opt) {
    opt = $.extend({
        type: 'alert',
        ensure: function () {
            dlg.layerHide()
        },
        cancel: function () {
            dlg.layerHide()
        },
        title: '提示信息',
        msg: '提示',
        ensure_t: '确 定',
        cancel_t: '取 消'
    }, opt);
    var dlg = $('<div class="floatBox01 hide" style="position:absolute;z-index:15"><div class="t01"><div class="fl"><span>' + opt.title + '</span></div><div class="fr"><span class="close01" name="btn_cancel"></span></div><div class="clear"></div></div><div class="c01"><div' + (opt.type != 'common' ? ' class="msg02"' : ' class="msg02"') + '>' + opt.msg + '</div><div class="tc pt01"><input type="button" name="btn_ensure" class="submit01" value="' + opt.ensure_t + '"/> <input type="button" name="btn_cancel" class="submit01" value="' + opt.cancel_t + '"/></div></div></div>');
    $(document.body).append(dlg);
    dlg.layerAutoReset().modal().shadow().layerReset();
    dlg.drag({
        handle: dlg.find('.t01:first')
    })
    dlg.ensure = dlg.find('[name=btn_ensure]').click(function () {
        opt.ensure();
    });
    dlg.cancel = dlg.find('[name=btn_cancel]').click(function () {
        opt.cancel();
    });
    if (null == opt.cancel_t || 0 == opt.cancel_t.length) dlg.find('input[name=btn_cancel]').remove();
    dlg.layerShow();
    dlg.bind('hide', function () {
        setTimeout(function () {
            dlg.remove();
        }, 30000);
    });
    return dlg;
}

function generatePage(opt) {
    var _gen = function (p, o) {
        return '#' + p;
    }
    opt = $.extend({
        url: _gen
    }, opt);
    var html = '';
    for (var i = 0; i < opt.pagination.pagebar.length; ++i) {
        var page = opt.pagination.pagebar[i];
        if (page == opt.pagination.cur_page) html += '<span class="current">' + page + '</span>';
        else
        html += '<a href="' + opt.url(page, opt) + '">' + page + '</a>';
    }
    html += '<span>|</span>';
    if (opt.pagination.first.link) html += '<a href="' + opt.url(1, opt) + '">首页</a>';
    else
    html += '<span>首页</span>';
    if (opt.pagination.prev.link) html += '<a href="' + opt.url(opt.pagination.prev.id, opt) + '">上页</a>';
    else
    html += '<span>上页</span>';
    if (opt.pagination.next.link) html += '<a href="' + opt.url(opt.pagination.next.id, opt) + '">下页</a>';
    else
    html += '<span>下页</span>';
    if (opt.pagination.last.link) html += '<a href="' + opt.url(opt.pagination.last.id, opt) + '">末页</a>';
    else
    html += '<span>末页</span>';
    return html;
}

function fromTimeStamp(ts) {
    var d = new Date(ts * 1000);
    return $.sprintf("%4d-%02d-%02d %02d:%02d:%02d", d.getFullYear(), (d.getMonth() + 1), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds());
}

function clearUrl(u) {
    var idx = u.indexOf('#');
    if (-1 != idx) return u.substring(0, idx);
    return u;
}

function stock_code(c) {
    if (c.length == 5) return c + '.HK';
    if (c % 100000 == 6 || c % 100000 == 9) return c + '.SH';
    return c + '.SZ';
}

function headTipInit() {}

function myScoreInit() {}

function scoreIconHtml(score) {
    var h = '';
    if (score.level) {
        for (var i = 0; i < score.icon.sun; ++i)
        h += '<font class="levelIco03"></font>';
        for (var i = 0; i < score.icon.moon; ++i)
        h += '<font class="levelIco02"></font>';
        for (var i = 0; i < score.icon.star; ++i)
        h += '<font class="levelIco01"></font>';
    } else {
        h = '<font class="levelIco00"></font>';
    }
    return h;
}

/**
 * [application common section] end
 */



/**
 * [twitter common section] begin
 */

function twOkDlg(cb) {
    if (typeof(cb) == 'undefined') cb = function () {};
    var ok = $('#ok_dlg').fadeIn().layerReset();
    setTimeout(function () {
        ok.fadeOut('fast', cb)
    }, 1500);
}

function twSearchUser(k) {
    if (typeof(G_RELATED_USER) != 'undefined') {
        var r = [];
        if (k.length) {
            var lower_k = k.toLowerCase();
            for (var id in G_RELATED_USER) {
                var idx = G_RELATED_USER[id][1].indexOf(lower_k);
                if (-1 != idx) {
                    r.push([G_RELATED_USER[id][0], idx]);
                    if (r.length >= 20) break;
                }
            }
        } else {
            for (var id in G_RELATED_USER) {
                r.push([G_RELATED_USER[id][0], -1]);
                if (r.length >= 20) break;
            }
        }
        return r;
    }
    return null;
}

function twSearchStock(k) {
    var kupper = k.toUpperCase();
    if (k.length && typeof(G_STOCK_LIST) != 'undefined') {
        var s = isNaN(parseInt(k)) ? 0 : 1;
        var r = [];
        for (var i in G_STOCK_LIST) {
            var n = (1 == s) ? G_STOCK_LIST[i].i : G_STOCK_LIST[i].n;
            var idx = n.indexOf(k);
            if (-1 != idx) {
                r.push([G_STOCK_LIST[i], idx, s]);
                if (r.length >= 20) break;
            } else if (0 == s || 2 == s) {
                if (typeof(G_STOCK_LIST[i]) != 'undefined') {
                    idx = G_STOCK_LIST[i].ps.indexOf(kupper);
                    if (-1 != idx) {
                        s = 2;
                        r.push([G_STOCK_LIST[i], idx, s]);
                        if (r.length >= 20) break;
                    }
                }
            }
        }
        return r;
    }
    return null;
}

function twPostBoxUniverseInit(t) {
    t.posting = 0;
    t.ta = t.co.find('textarea').bind($.browser.msie ? 'propertychange' : 'input', function (e) {
        if ($.browser.msie && event.propertyName != 'value') return;
        t.count();
    }).bind('keyup', function (e) {
        if (e.keyCode == 13) {
            if (e.ctrlKey) t.post();
        } else if (e.keyCode == 115) {
            if (e.altKey) t.post();
        }
    });
    var prepend_topic_id = t.ta.attr('prepend_topic_id');
    if (typeof(prepend_topic_id) != 'undefined' && prepend_topic_id.length > 0) t.ta.topic = {
        id: prepend_topic_id,
        key: t.ta.val()
    };
    else
    t.ta.topic = {
        id: 0,
        key: ''
    };
    t.ta.at = new TwitterAt({
        textarea: t.ta,
        tb: t
    });
    t.ta.at.init();
    t.count = function () {
        if (t.auto_height) {
            if (typeof(t.auto_height_min) == 'undefined') t.auto_height_min = 19;
            var h = t.ta.get(0).scrollHeight;
            h = Math.max(t.auto_height_min, parseInt((h + 2) / 19) * 19);
            t.ta.css('height', h);
        }
        if (null == t.count.d) {
            t.count.d = t.co.find('.countTxt:last');
            t.count.d.ct = t.count.d.find('span:first');
            t.count.d.font = t.count.d.ct.find('font');
            t.count.d.em = t.count.d.ct.find('em');
            t.count.d.msg = t.count.d.find('span:last');
        }
        var v = t.ta.val();
        var w = v.width();
        var l = parseInt(w / 2) + w % 2;
        var m = 140;
        var too_much = false;
        if (!too_much) {
            var mat = v.match(/(http|https):\/\/[0-9a-zA-Z\/%\-&\?=@:\._,#]+/g);
            if (mat) {
                for (var i = 0; i < mat.length; ++i) {
                    l = l - mat[i].length + 21;
                }
                if (l > m) too_much = true;
            } else {
                if (l > m) too_much = true;
            }
        }
        if (too_much) {
            t.count.d.em.addClass('orange').text(l - m);
            t.count.d.font.text('超过');
            t.count.d.ct.show();
            t.count.d.msg.hide();
            return false;
        } else {
            t.count.d.em.removeClass('orange').text(m - l);
            t.count.d.font.text('还能输入');
            t.count.d.ct.show();
            t.count.d.msg.hide();
            return true;
        }
    };
    t.show_posting = function () {
        var c = t.co.find('.countTxt:last').hide();
        c.prev().show();
    };
    t.show_counting = function () {
        var c = t.co.find('.countTxt:first').hide();
        c.next().show();
    }
    t.delay_focus = function (cb) {
        setTimeout(function () {
            t.ta.focus();
            if (typeof(cb) != 'undefined') cb();
            t.count();
        }, 10);
    };
    t.msg = function (m) {
        if (null == t.count.d) t.count();
        t.count.d.ct.hide();
        t.count.d.msg.text(m).show();
    };
    t.new_topic = function () {
        if ($.browser.msie) t.delay_focus(t.real_new_topic);
        else
        t.real_new_topic();
    };
    t.real_new_topic = function () {
        var cp = t.ta.caretPosition();
        var val = t.ta.val();
        var ins = '#创建想要交流的话题#';
        var idx = val.indexOf(ins);
        if (-1 == idx) {
            var nv = val.substring(0, cp.start) + ins + val.substr(cp.end);
            t.ta.val(nv);
            t.ta.caretPosition(cp.start + 1, ins.length - 2);
            t.count();
        } else {
            t.ta.caretPosition(idx + 1, ins.length - 2);
        }
    };
    t.new_stock_topic_text = '';
    t.new_stock_topic = function (stock_text) {
        t.new_stock_topic_text = stock_text;
        if ($.browser.msie) t.delay_focus(t.real_new_stock_topic);
        else
        t.real_new_stock_topic();
    };
    t.real_new_stock_topic = function () {
        var cp = t.ta.caretPosition();
        var val = t.ta.val();
        var ins = '#' + t.new_stock_topic_text + '#';
        var idx = val.indexOf(ins);
        if (-1 == idx) {
            var nv = val.substring(0, cp.start) + ins + val.substr(cp.end);
            t.ta.val(nv);
            t.ta.caretPosition(cp.start + ins.length, 0);
            t.count();
        } else {
            t.ta.caretPosition(idx + 1, ins.length - 2);
        }
    };
    t.post = function () {

    };

}


function TwitterAt(o) {
    if (o.textarea.length == 0) console.trace();
    var t = this;
    t.o = o;
    t.inited = false;
    t.init = function () {
        if (t.inited) return;
        t.inited = true;
        t.tip_showing = false;
        t.list_del_sel = 0;
        t.ta = t.o.textarea;
        t.ta.blur(function () {
            if (TwitterAtTipsInstance().mouseover == 0) setTimeout(function () {
                t.hide()
            }, 10);
        });
        t.set_list_default_sel = function (i) {
            t.list_del_sel = i;
        };
        t.hide = function () {
            TwitterAtTipsInstance().hide();
        };
        t.check = function () {
            var ret = TwitterAtTipsInstance().check(t.ta, t.list_del_sel);
            if (ret) t.check_res = ret;
            return ret;
        };
        t.sel_callback = null;
        TwitterAtTipsInstance().registerNotice(function () {
            t.tip_showing = true;
            if (TwitterAtTipsInstance().ta != t.ta) return;
            t.ta.bind('keydown', t.onkeydown);
        }, function () {
            t.tip_showing = false;
            if (TwitterAtTipsInstance().ta != t.ta) return;
            t.ta.unbind('keydown', t.onkeydown);
        }, (t.ta.get(0).tagName == 'TEXTAREA') ?
        function (e, mode, name, id, sa) {
            if (TwitterAtTipsInstance().ta != t.ta) return;
            if (mode == 'user') {
                if (t.check_res.cpat >= 0) {
                    var cp = t.ta.caretPosition().start;
                    if (cp == -1) t.ta.caretReplace(name + ' ', t.check_res.cpat + 1);
                    else
                    t.ta.caretReplace(name + ' ', t.check_res.cpat + 1, cp - t.check_res.cpat - 1);
                    t.ta.caretPosition(t.check_res.cpat + 1 + name.length + 1);
                } else {
                    t.ta.caretReplace(name + ' ');
                }
            } else {
                //var nv='#'+name+'('+id+'.'+sa+')#';
                var nv = '#' + name + '#';
                if (t.check_res.cppd >= 0) {
                    var cp = t.ta.caretPosition().start;
                    if (cp == -1) {
                        t.ta.caretReplace(nv, t.check_res.cppd, 1);
                        t.ta.caretPosition(t.check_res.cppd + 1 + nv.length + 1);
                    } else {
                        if (t.check_res.cppde > 0) t.ta.caretReplace(nv, t.check_res.cppd, t.check_res.key.length + 2);
                        else
                        t.ta.caretReplace(nv, t.check_res.cppd, t.check_res.key.length + 1);
                        t.ta.caretPosition(t.check_res.cppd + nv.length);
                    }
                } else {
                    t.ta.caretReplace(nv);
                }
            }
            if (typeof(t.o.tb) != 'undefined') t.o.tb.count();
            if (t.sel_callback) t.sel_callback(e, mode, name, id, sa);
        } : function (e, mode, name, id, sa) {
            if (TwitterAtTipsInstance().ta != t.ta) return;
            if (mode == 'user') {
                t.ta.get(0).value = name;
            } else {
                t.ta.get(0).value = name + '(' + id + '.' + sa + ')';
            }
            if (t.sel_callback) t.sel_callback(e, mode, name, id, sa);
        });
        t.old_cp = -1;
        t.oninput = function (e) {
            if ($.browser.msie && event.propertyName != 'value') return;
            if (t.old_cp == -1) {
                if ($.browser.safari) {
                    var cp = t.ta.caretPosition().start;
                    t.ta.caretPosition(cp + 1);
                }
                t.check();
            }
        };
        t.onkeyup = function (e) {
            if (t.old_cp != -1) {
                t.ta.caretPosition(t.old_cp);
                t.old_cp = -1;
            } else {
                if (e.keyCode == 13) {
                    if (!e.ctrlKey) t.hide();
                } else if (e.keyCode >= 37 && e.keyCode <= 40) {
                    t.check();
                }
            }
        };
        t.onkeydown = function (e) {
            var get_old_cp = true;
            if (e.keyCode == 38) TwitterAtTipsInstance().selectUp();
            else if (e.keyCode == 40) TwitterAtTipsInstance().selectDown();
            else if (e.keyCode == 13) get_old_cp = TwitterAtTipsInstance().selectCurrent();
            else if (e.keyCode == 27) TwitterAtTipsInstance().hide();
            else
            get_old_cp = false;
            t.old_cp = get_old_cp ? t.ta.caretPosition().start : -1;
            if (t.old_cp != -1) return false;
        };
        t.ta.bind($.browser.msie ? 'propertychange' : 'input', t.oninput).bind('keyup', t.onkeyup).bind('click', t.check);
        return t;
    }
}

var G_TWATTIPS = null;

function TwitterAtTipsInstance() {
    if (null == G_TWATTIPS) {
        G_TWATTIPS = new TwitterAtTips();
        G_TWATTIPS.init();
    }
    return G_TWATTIPS;
}

function twAtClick(o) {
    var t = TwitterAtTipsInstance();
    twAtMouseOver(o);
    t.selectCurrent(o);
}

function twAtMouseOver(o) {
    var t = TwitterAtTipsInstance();
    t.d.c.find('a.ahover').removeClass('ahover');
    $(o).addClass('ahover');
}

function TwitterAtTips() {
    var t = this;
    t.inited = false;
    t.init = function () {
        if (t.inited) return;
        t.inited = true;
        t.d = $('#at_user_tipis').hover(function () {
            t.mouseover = 1;
        }, function () {
            t.mouseover = 0;
        });
        t.d.c = t.d;
        t.registerNotice = function (cbshow, cbhide, cbsel) {
            t.d.bind('show', cbshow);
            t.d.bind('hide', cbhide);
            t.d.bind('sel', cbsel);
        };
        t.check = function (jqta, list_def_sel) {
            t.ta = jqta;
            var ret = null;
            if (1 != jqta.attr('disable_at')) {
                var ret = t.get_at_str();
                if (null != ret) {
                    var r = twSearchUser(ret.key);
                    if (r) {
                        if (typeof(list_def_sel) == 'undefined') list_def_sel = 0;
                        var chkres = t.render_user_list(r, ret.key, ret.cpat, list_def_sel);
                        return chkres ? ret : null;
                    }
                }
            }
            if (1 != jqta.attr('disable_pd')) {
                ret = t.get_pd_str();
                if (null != ret) {
                    var r = twSearchStock(ret.key);
                    if (r) {
                        if (typeof(list_def_sel) == 'undefined') list_def_sel = 0;
                        var chkres = t.render_stock_list(r, ret.key, ret.cppd, list_def_sel);
                        return chkres ? ret : null;
                    }
                    return null;
                }
            }
            t.hide();
            return null;
        };
        t.show = function () {
            if (t.d.length && t.d.get(0).style.display == 'none') t.d.layerShow();
        }
        t.hide = function () {
            if (t.d.length && t.d.get(0).style.display != 'none') t.d.layerHide();
        };
        t.selectUp = function () {
            var d = t.d.c.find('a.ahover');
            if (d.length) {
                var n = d.prev();
                if (n.length) {
                    d.removeClass('ahover');
                    n.addClass('ahover');
                    var dct = n.offset().top - t.d.c.offset().top;
                    if (dct < 0) t.d.c.scrollTop(dct + t.d.c.scrollTop());
                }
            } else {
                t.d.c.find('a:first').addClass('ahover');
            }
        };
        t.selectDown = function () {
            var d = t.d.c.find('a.ahover');
            if (d.length) {
                var n = d.next();
                if (n.length) {
                    d.removeClass('ahover');
                    n.addClass('ahover');
                    var ct = t.d.c.scrollTop();
                    var ch = t.d.c.height();
                    var dh = n.height();
                    var dct = n.offset().top - t.d.c.offset().top;
                    if (dct + dh > ch) t.d.c.scrollTop(dct + dh - ch + ct);
                }
            } else {
                t.d.c.find('a:first').addClass('ahover');
            }
        };
        t.selectCurrent = function (o) {
            var d = t.d.c.find('a.ahover');
            if (d.length) {
                var mode = t.d.c.attr('mode');
                if (mode == 'user') t.d.trigger('sel', [mode, d.attr('n')]);
                else
                t.d.trigger('sel', [mode, d.attr('n'), d.attr('i'), d.attr('sa')]);
                t.hide();
                return true;
            } else {
                return false;
            }
        };
        t.render_user_list = function (list, key, cpat, list_def_sel) {
            if (typeof(list) == 'undefined' || !list || list.length == 0) t.hide();
            else {
                t.d.c.empty().attr('mode', 'user');
                for (var i = 0; i < list.length; ++i) {
                    var n = list[i][0];
                    var idx = list[i][1];
                    var d = $('<a href="#" onmouseup="twAtClick(this);return false;" onmouseover="twAtMouseOver(this)" onClick="return false;"></a>').attr('n', n);
                    var html = '';
                    if (-1 != idx) {
                        if (idx != 0) html += d.text(n.substring(0, idx)).html();
                        html += '<b>' + d.text(n.substr(idx, key.length)).html() + '</b>';
                        if (idx + key.length < n.length) html += d.text(n.substr(idx + key.length)).html();
                    } else {
                        html = d.text(n).html();
                    }
                    d.html(html);
                    if (list_def_sel == i) d.addClass('ahover');
                    t.d.c.append(d);
                }
                var atos = t.ta.caretOffset(cpat);
                t.d.css('left', atos.left).css('top', atos.top + 20);
                t.show();
                return true;
            }
            return false;
        };
        t.render_stock_list = function (list, key, cppd, list_def_sel) {
            var kupper = key.toUpperCase();
            if (typeof(list) == 'undefined' || !list || list.length == 0) t.hide();
            else {
                t.d.c.empty().attr('mode', 'stock');
                for (var i = 0; i < list.length; ++i) {
                    var stock = list[i][0];
                    var sid = stock.i;
                    var sname = stock.n;
                    var sps = stock.ps;
                    var idx = list[i][1];
                    var ss = list[i][2];
                    var sa = 'HK';
                    if (sid.length == 6) {
                        var st = sid.substr(0, 1);
                        if ('6' == st || '9' == st) sa = 'SH';
                        else
                        sa = 'SZ';
                    }
                    var d = $('<a href="#" onmouseup="twAtClick(this);return false;" onmouseover="twAtMouseOver(this)" onClick="return false;"></a>').attr('n', sname).attr('i', sid).attr('sa', sa);
                    var html = '';
                    if (ss == 0) {
                        if (idx != 0) html += d.text(sname.substring(0, idx)).html();
                        html += '<b>' + d.text(key).html() + '</b>';
                        if (idx + key.length < sname.length) html += d.text(sname.substr(idx + key.length)).html();
                        html += '(' + sid + '.' + sa + ')&nbsp;' + sps;
                    } else if (ss == 1) {
                        html += d.text(sname + '(').html();
                        if (idx != 0) html += d.text(sid.substring(0, idx)).html();
                        html += '<b>' + d.text(key).html() + '</b>';
                        if (idx + key.length < sid.length) html += d.text(sid.substr(idx + key.length)).html();
                        html += '.' + sa + ')&nbsp;' + sps;
                    } else {
                        html += sname + '(' + sid + '.' + sa + ')&nbsp;';
                        if (idx != 0) html += sps.substring(0, idx);
                        html += '<b>' + kupper + '</b>';
                        if (idx + key.length < sps.length) html += sps.substr(idx + key.length);
                    }
                    d.html(html);
                    if (list_def_sel == i) d.addClass('ahover');
                    t.d.c.append(d);
                }
                var atos = t.ta.caretOffset(cppd);
                t.d.css('left', atos.left).css('top', atos.top + 20);
                t.show();
                return true;
            }
            return false;
        };
        t.get_at_str = function () {
            var v = t.ta.get(0).value
            try {
                var cp = t.ta.caretPosition().start;
            } catch (e) {
                return null;
            }
            var ret = {
                key: '',
                cpat: 0
            };
            if (t.ta.get(0).tagName == 'TEXTAREA') {
                var suf = '';
                var line = v.substring(0, cp);
                var bridx = line.lastIndexOf('\n');
                if (bridx != -1) {
                    line = line.substr(bridx + 1);
                    ret.cpat = bridx + 1;
                }
                var atidx = line.lastIndexOf('@');
                if (atidx == -1) return null;
                ret.cpat += atidx;
                line = line.substr(atidx + 1);
                mat = line.match(/^([^\s@#]*)$/);
                if (mat) line = mat[1];
                else
                return null;
                ret.key = line + suf;
                if (ret.key.length) return ret;
                else if (cp == ret.cpat + 1) return ret;
                return null;
            } else {
                ret.key = v.substring(0, cp);
                return ret;
            }
        };
        t.get_pd_str = function () {
            var v = t.ta.get(0).value
            try {
                var cp = t.ta.caretPosition().start;
            } catch (e) {
                return null;
            }
            var ret = {
                key: '',
                cppd: 0,
                cppde: 0
            };
            if (t.ta.get(0).tagName == 'TEXTAREA') {
                var suf = v.substr(cp);
                var mat = suf.match(/^([^#]*)#/);
                if (mat) {
                    suf = mat[1];
                    ret.cppde = cp + suf.length;
                } else {
                    suf = '';
                }
                var line = v.substring(0, cp);
                var bridx = line.lastIndexOf('\n');
                if (bridx != -1) {
                    line = line.substr(bridx + 1);
                    ret.cppd = bridx + 1;
                }
                var pdidx = line.lastIndexOf('#');
                if (pdidx == -1) return null;
                ret.cppd += pdidx;
                var matpd = line.match(/#/g);
                if (matpd.length % 2 == 0) return null;
                line = line.substr(pdidx + 1);
                mat = line.match(/^([^\s#]*)$/);
                if (mat) line = mat[1];
                else
                return null;
                ret.key = line + suf;
                if (ret.key.length) return ret;
                return null;
            } else {
                ret.key = v.substring(0, cp);
                return ret;
            }
        };
    }
}

var G_TWTB = null;

function twTbInstance() {
    if (null == G_TWTB) {
        G_TWTB = new TwitterTalkBox();
        G_TWTB.init();
    }
    return G_TWTB;
}

function twTbMakeFocus() {
    var ta = twTbInstance().ta;
    ta.focus();
}

function twTbFocus() {
    twTbInstance().ta.addClass('focus');
}

function twTbBlur() {
    twTbInstance().ta.removeClass('focus');
}

function twTbNewTopic() {
    twTbInstance().new_topic();
}

function twTbNewStockTopic(t) {
    twTbInstance().new_stock_topic(t);
}

function twTbPost() {
    twTbInstance().post();
}

function twTbPicMouseOver(o) {
    $(o).children('[name=up]').addClass('underline');
}

function twTbPicMouseOut(o) {
    $(o).children('[name=up]').removeClass('underline');
}

function twTbPicSel() {
    if (!twCheckLogon()) return;
    twTbInstance().pic_sel();
}

function twTbPicRet(ret) {
    twTbInstance().pic_ret(ret);
}

function twTbPicCancel() {
    twTbInstance().pic_cancel();
}

function TwitterTalkBox() {
    var t = this;
    t.inited = false;
    t.init = function () {
        if (t.inited) return;
        t.inited = true;
        t.auto_height = 0;
        t.co = $('#talkBox');
        t.co.ensure = t.co.find(':button.sendBtn');
        twPostBoxUniverseInit(t);
        t.cbCollectPostData = function (dt) {
            dt.photo_id = t.up.photo_id;
            var ptid = t.ta.topic.id;
            if (ptid > 0) dt.prepend_topic_id = ptid;
            return true;
        };
        t.cbAfterPostSuccess = function (ret, dt) {
            if (0 == ret.result) {
                t.pic_cancel();
                if (dt && dt.prepend_topic_id) {
                    var found = 0;
                    for (var i = 0; i < ret.msg.topic_id_list.length; ++i) {
                        var topic_id = ret.msg.topic_id_list[i];
                        if (topic_id == dt.prepend_topic_id) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        twOkDlg();
                        return;
                    }
                }
                if (0 == twMsgPrepend(ret.msg)) twOkDlg();
            }
        };
        t.up = {};
        t.up.photo_id = '';
        t.up.fm = t.co.find('form');
        t.up.co = t.up.fm.parent();
        t.up.btn = t.up.fm.find('input');
        t.up.up = t.up.co.find('[name=up]');
        t.up.uping = t.up.co.find('[name=uping]');
        t.up.uped = t.up.co.find('[name=uped]');
        t.pic_sel = function () {
            t.up.up.hide();
            t.up.uping.show();
            t.up.fm.submit();
            var n = t.up.btn.val();
            var np = Math.max(n.lastIndexOf('/'), n.lastIndexOf('\\'));
            var fn = n.substr(np + 1);
            if (fn.length > 14) fn = fn.substr(0, 5) + '...' + fn.substr(fn.length - 8);
            t.up.file_name = fn;
        };
        t.pic_ret = function (ret) {
            if (0 == ret.result) {
                t.up.photo_id = ret.photo_id;
                t.up.uping.hide();
                t.up.uped.show().text(t.up.file_name + '[删除]');
                t.up.btn.val('');
                if (t.ta.val().length == 0) {
                    t.ta.val('#分享图片#');
                    t.ta.caretPosition(6);
                }
            } else {
                t.pic_cancel();
            }
        };
        t.pic_cancel = function () {
            t.up.photo_id = '';
            $('#imageUpload').get(0).src = 'about:blank';
            t.up.uping.hide();
            t.up.uped.hide();
            t.up.up.show();
            t.up.btn.val('');
        };
    };
}

G_VARS.select_stock_dlg = null;

function twSelectStockShow(mode) {
    var dlg;
    if (null == G_VARS.select_stock_dlg) {
        dlg = G_VARS.select_stock_dlg = $('#select_stock_dlg').layerAutoReset().modal().shadow();
        dlg.drag({
            handle: dlg.find('.t01:first')
        });
        dlg.find('.close01').click(function () {
            dlg.layerHide();
            dlg.at.hide();
            if (0 == dlg.mode) {
                twSelectStockSynchSort();
            } else {}
        });
        dlg.ensure = dlg.find('[name=ensure]').click(function () {
            dlg.submit()
        });
        dlg.key = dlg.find('input[name=key]');
        dlg.at = new TwitterAt({
            textarea: dlg.key
        });
        dlg.at.init();
        dlg.at.sel_callback = function () {
            dlg.submit();
        };
        dlg.submit = function () {
            var val = dlg.key.val();
            var mat = val.match(/[\w\W]+\((\d{5,6})\.[a-zA-Z]{2}\)/);
            if (mat) {
                if (0 == parseInt(dlg.attr('mode'))) {
                    var code = mat[1];
                    twFollowStock(code, 1, function (dt, ret) {
                        twSelectStockAppendFollowList(code, ret.map.stock[code]);
                        dlg.list.parents('div').scrollTop(1000);
                        setTimeout(function () {
                            dlg.key.caretPosition(0, dlg.key.val().length);
                        }, 10);
                    });
                } else {
                    twTbNewStockTopic(val);
                    setTimeout(function () {
                        dlg.layerHide();
                    }, 1);
                    dlg.at.hide();
                }
            }
        };
        dlg.follow_list = dlg.find('[name=follow_stocks]');
    } else
    dlg = G_VARS.select_stock_dlg;
    dlg.layerShow().layerReset().attr('mode', mode);
    if (0 == mode) {
        dlg.find('[name=title]').text('编辑或添加自选股');
        twSelectStockRefreshFollowList();
    } else {
        dlg.find('[name=title]').text('插入想要交流的股票');
        dlg.follow_list.hide();
    }
    setTimeout(function () {
        dlg.key.caretPosition(0, dlg.key.val().length);
    }, 1);
    dlg.mode = mode;
}

function twSelectStockRefreshFollowList() {
    var dt = {};
    dt.of = 'json';
    dt.stock_num = 15;
    dt.simple = 1;
    $.ajax({
        url: '/' + G_USER_ID + '/stock',
        async: true,
        dataType: 'json',
        type: 'GET',
        data: dt,
        cache: false,
        success: function (ret) {
            if (0 == ret.result) {
                var dlg = G_VARS.select_stock_dlg;
                if (typeof(dlg.sample) == 'undefined') {
                    dlg.sample = dlg.find('[name=sample]');
                    dlg.list = dlg.sample.parent();
                    dlg.sample.find('[name=up]').click(function () {
                        var d = $(this).parents('[name=stock]');
                        var prev = d.prev('[name=stock]');
                        if (prev.length) prev.before(d);
                    });
                    dlg.sample.find('[name=down]').click(function () {
                        var d = $(this).parents('[name=stock]');
                        var next = d.next('[name=stock]');
                        if (next.length) next.after(d);
                    });
                    dlg.sample.find('[name=del]').click(function () {
                        var code = $(this).parents('[name=stock]').attr('code');
                        twFollowStock(code, 0, function () {
                            dlg.list.find('[name=stock][code=' + code + ']').remove();
                            if (0 == dlg.list.find('[name=stock]').length) dlg.follow_list.hide();
                        });
                    });
                }
                dlg.list.find('[name=stock]').remove();
                if (ret.stock_list.length) {
                    dlg.follow_list.show();
                    for (var i = 0; i < ret.stock_list.length; ++i) {
                        var fst = ret.stock_list[i];
                        var code = fst['code'];
                        var stock = ret.map.stock[code];
                        twSelectStockAppendFollowList(code, stock);
                    }
                    dlg.layerReset();
                } else {
                    dlg.follow_list.hide();
                }
            } else {
                dbg('twSelectStockRefreshFollowList ret=' + errorInfo(ret.result).msg);
            }
        },
        error: function () {
            dbg("twSelectStockRefreshFollowList err");
        }
    });
}

function twSelectStockAppendFollowList(code, stock) {
    var dlg = G_VARS.select_stock_dlg;
    if (dlg.list.find('[name=stock][code=' + code + ']').length) return;
    var d = dlg.sample.clone(true).show().attr('name', 'stock').attr('code', code);
    d.find('[name=name]').text(stock.info.name);
    d.find('[name=code]').text(stock.info.code);
    var dp = d.find('[name=price]').text(stock.daily.price / 1000);
    var dd = d.find('[name=delta]').text(stock.daily.delta_percent);
    if (stock.daily.delta <= 0) {
        dp.removeClass('up');
        dd.removeClass('up');
        if (stock.daily.delta == 0) {
            dp.addClass('flat');
            dd.addClass('flat');
        } else {
            dp.addClass('down');
            dd.addClass('down');
        }
    }
    dlg.list.append(d);
    dlg.follow_list.show();
}

function twSelectStockSynchSort() {
    var dlg = G_VARS.select_stock_dlg;
    var list = [];
    var slist = dlg.list.find('[name=stock]');
    var len = slist.length;
    for (var i = 0; i < slist.length; ++i) {
        var st = {
            code: slist.eq(i).attr('code')
        };
        st.sort = len - i;
        list.push(st);
    }
    var dt = {};
    dt.of = 'json';
    dt.list = list;
    $.ajax({
        url: '/twitter/follow_stock_sort',
        async: true,
        dataType: 'json',
        type: 'POST',
        data: dt,
        cache: false,
        success: function (ret) {
            if (0 == ret.result) {
                var o = $('#right_following_stock');
                if (o.length) twShowRightFollowingStock(o.get(0));
                if (window.location.href.match(/\/t\.futu\.cn\/\d+\/stock(\?.*)?/)) {
                    twFollowingStocksRefresh();
                    $('[name=msg_list]').children('li[name=msg]').remove();
                    twMsgInstance().load_more();
                }
            } else {
                dbg('twSelectStockSynchSort ret=' + errorInfo(ret.result).msg);
            }
        },
        error: function () {
            dbg("twSelectStockSynchSort err");
        }
    });
}

function twFollowingStocksRefresh() {
    var ul = $('[name=follow_stock_ul]');
    if (ul.length == 0) return;
    var dt = {};
    dt.of = 'json';
    dt.stock_num = 15;
    dt.simple = 1;
    $.ajax({
        url: '/' + G_USER_ID + '/stock',
        async: true,
        dataType: 'json',
        type: 'GET',
        data: dt,
        cache: false,
        success: function (ret) {
            if (0 == ret.result) {
                ul.children('[name=stock]').remove();
                if (ret.stock_list.length) {
                    ul.parent().show();
                    $('#none_stock').hide();
                    var sample = ul.children('[name=sample]');
                    for (var i = 0; i < ret.stock_list.length; ++i) {
                        var fst = ret.stock_list[i];
                        var code = fst['code'];
                        var stock = ret.map.stock[code];
                        var d = sample.clone().show().attr('name', 'stock');
                        d.find('[name=name]').text(stock.info.name + '(' + stock.other.code_type + ')').attr('href', '/' + stock.other.code_type);
                        var dp = d.find('[name=price]').text(stock.daily.price / 1000);
                        var dd = d.find('[name=delta]').text(stock.daily.delta_percent);
                        if (stock.daily.delta <= 0) {
                            dp.removeClass('up');
                            dd.parent().removeClass('up');
                            if (stock.daily.delta < 0) {
                                dp.addClass('down');
                                dd.parent().addClass('down');
                            } else {
                                dp.addClass('flat');
                                dd.parent().addClass('flat');
                            }
                        }
                        ul.append(d);
                    }
                    if (ret.stock_list.length % 2 != 0) ul.append($('<li style="cursor:default" name="stock"></li>'))
                } else {
                    ul.parent().hide();
                    $('#none_stock').show();
                }
            } else {
                dbg('twFollowingStocksRefresh ret=' + errorInfo(ret.result).msg);
            }
        },
        error: function () {
            dbg("twFollowingStocksRefresh err");
        }
    });
}
var G_TWMAIL = null;

function twMailInstance() {
    if (null == G_TWMAIL) {
        G_TWMAIL = new TwitterMail();
        G_TWMAIL.init();
    }
    return G_TWMAIL;
}

function twMailDlgShow(un) {
    twMailInstance().show_dlg(un);
}

function twMailRemove(o) {
    twMailInstance().del_confirm(o)
}

function TwitterMail() {
    var t = this;
    t.inited = false;
    t.init = function () {
        if (t.inited) return;
        t.inited = true;
        t.auto_height = 0;
        t.co = t.d = $('#post_mail').layerAutoReset().modal();
        twPostBoxUniverseInit(t);
        t.d.n = t.d.find('[name=n]');
        t.post = function (o) {
            if (!t.count()) return;
            var dt = {};
            dt.of = 'json';
            dt.content = t.ta.val();
            dt.content = dt.content.replace(/#插入新话题#/g, '');
            dt.name = t.d.n.val();
            dt = $.extend(o, dt);
            if (dt.name.length == 0) return t.msg("请先填写收件人");
            if (dt.content.length == 0) return t.msg("请先填写内容");
            var res = check_recv(dt.name);
            if (res == 404) {
                return t.msg(dt.name + " 不存在！");
            }
            if (res == 403) {
                return t.msg(dt.name + " 没跟随您，还不能给他发私信！");
            }

            $.ajax({
                url: '/msg/send_one',
                type: 'POST',
                data: {
                    'text': dt.content,
                    'to_uid': dt.name
                },
                success: function () {
                    t.ta.val('');
                    t.count();
                    t.hide_dlg();
                    twOkDlg();

                },
                error: function () {
                    t.msg("发表出错，请稍后再试。");
                    if (typeof(t.cbAfterPostErr) != 'undefined') t.cbAfterPostErr();
                }
            });
        };
        t.d.find('.closeBtn02').click(function () {
            t.hide_dlg();
        });
        t.d.find('.submit04').click(function () {
            t.post();
        });
        t.show_dlg = function (un) {
            t.d.layerShow().layerReset();
            t.ta.val('');
            t.d.n.val(un);
            if (un.length) {
                t.ta.focus();
                t.d.n.at.hide();
            } else {
                t.d.n.focus()
                t.d.n.at.check();
            }
        };
        t.hide_dlg = function () {
            t.ta.at.hide();
            t.d.layerHide();
        };
        t.d.n.at = new TwitterAt({
            textarea: t.d.n
        });
        t.d.n.at.init();
        t.init_del = function () {
            if (null == t.d.d) {
                t.d.d = $('#delete_mail_confirm');
                if (t.d.d.length == 0) {
                    t.d.d = $('#delete_msg_confirm').clone().attr('id', 'delete_mail_confirm');
                    $(document.body).append(t.d.d);
                }
                t.d.d.find('[name=info]').text('确定删除这条私信？');
                var btns = t.d.d.find('input');
                btns.eq(0).click(function () {
                    t.remove(t.d.d.attr('del_mid'), t.d.d.attr('outbox'));
                });
                btns.eq(1).click(function () {
                    t.d.d.layerHide();
                });
            }
            return t.d.d;
        };
        t.del_confirm = function (o) {
            var os = $(o).offset();
            var d = $(o).parents('li[mid]');
            t.init_del().css('left', os.left - 20).css('top', os.top - 20).layerShow().attr('del_mid', d.attr('mid')).attr('outbox', d.attr('outbox'));
        }
        t.remove = function (mid, outbox) {
            var dt = {};
            dt.of = 'json';
            dt.id = mid;
            dt.box = outbox;
            $.ajax({
                url: '/twitter/note_delete',
                async: true,
                dataType: 'json',
                type: 'POST',
                data: dt,
                success: function (ret) {
                    if (0 == ret.result) {
                        var d = $('li[mid=' + mid + ']');
                        d.remove();
                        t.init_del().layerHide();
                    } else {
                        alert(errorInfo(ret.result).msg);
                    }
                },
                error: function () {
                    alert("删除出错，请稍后再试。");
                }
            });
        };
        t.auto_check_unread = function () {
            t.check_unread();
            setInterval(function () {
                t.check_unread()
            }, 10 * 60000);
        };
    };
}

function check_recv(uid) {
    var res = 200;
    $.ajax({
        type: 'GET',
        url: "/check_receiver",
        data: {
            'recv': uid
        },
        async: false,
        success: function (data) {
            res = data;
        }
    });

    return res;
}
/**
 * [twitter common section] end
 */